//
//  EditViewController.m
//  dhfsAPP
//
//  Created by Devil on 2017/8/2.
//  Copyright © 2017年 Devil. All rights reserved.
//

#import "EditViewController.h"
#import "fsapp-Swift.h"
@interface EditViewController ()

@property(strong,nonatomic)EditView *editView;

@property(strong,nonatomic)NSDictionary *userInfoDic;

@property(strong,nonatomic)OSSClient *client;

@end

@implementation EditViewController{
    UIImage *image;
    NSString *imgUrl;
    BOOL isChoose;
}
#pragma mark - 懒加载
-(EditView *)editView{
    if (!_editView) {
        _editView = [[EditView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        
        _editView.headerView.headerViewDelegate = self;
        
        _editView.editViewDelegate = self;
    }
    
    return _editView;
}

-(EditView *)editView:(NSDictionary *)userInfo{
    if (!_editView) {
        _editView = [[EditView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) UserInfo:userInfo];
        
        _editView.headerView.headerViewDelegate = self;
        
        _editView.editViewDelegate = self;

    }
    
    return _editView;
}

#pragma mark - 系统自动调用函数
- (void)viewDidLoad {
    self.navigationController.navigationBarHidden = YES;
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self.view addSubview:self.editView];
    
    

    [SVProgressHUD showWithStatus:@"获取个人信息中"];
    [self getUserMessage];
    
    
    
    image = nil;
    isChoose = false;
    [self initALi];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - HeaderViewDelegate实现
-(void)clickHeaderViewBtn{
    [self.navigationController popViewControllerAnimated:true];
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 阿里云存储
//阿里云初始化
-(void)initALi{
    id<OSSCredentialProvider>credential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:@"zlN0arcl6DMQpBTf" secretKey:@"STDVRcq9CmVa7J6Iv2Y4l4LMweG48A"];
    
    OSSClientConfiguration *conf = [OSSClientConfiguration new];
    
    //网络请求遇到异常失败后重复的次数
    conf.maxRetryCount = 3;
    
    //网络请求超时事件
    conf.timeoutIntervalForRequest = 30;
    
    //允许资源传输的最长时间
    conf.timeoutIntervalForResource = 24*60*60;
    
    //阿里地址
    _client = [[OSSClient alloc] initWithEndpoint:@"http://oss-cn-shenzhen.aliyuncs.com" credentialProvider:credential];
    
}

-(void)updateToALi:(NSData *)data{
    OSSPutObjectRequest *put = [OSSPutObjectRequest new];
    
    put.bucketName = @"dahan-img";
    
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:0];
    
    NSTimeInterval a = [date timeIntervalSince1970];
    
    NSInteger x= (NSInteger)a;

    date = [NSDate date];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd"];
    
    NSString *dateTime = [formatter stringFromDate:date];
    
    NSString *objectKey = [NSString stringWithFormat:@"Picture/head/%@/%ld_%d%d%d%d%d%d.jpg",dateTime,(long)x,arc4random()%10,arc4random()%10,arc4random()%10,arc4random()%10,arc4random()%10,arc4random()%10];
    
    NSString *str = [NSString stringWithFormat:@"http://img.dahan.cn/%@",objectKey];
    
    imgUrl = [NSString stringWithFormat:@"http://dahan-img.oss-cn-shenzhen.aliyuncs.com/%@",objectKey];

    put.objectKey = objectKey;
    put.uploadingData = data;
    put.uploadProgress = ^(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend) {
        NSLog(@"%lld,%lld,%lld",bytesSent,totalBytesSent,totalBytesExpectedToSend);
    };
    
    OSSTask *putTask = [_client putObject:put];
    
    [putTask continueWithBlock:^id _Nullable(OSSTask * _Nonnull task) {
        NSLog(@"1");
        if (!task.error) {
            NSLog(@"上传成功");
//            [SVProgressHUD showSuccessWithStatus:@"上传成功"]
            [self changeInfo];
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:@"上传失败,请确认网络后再试"];
        }
        
        return nil;
    }];
    
//    [putTask waitUntilFinished];
}


-(void)updateToALi2:(NSData *)data Code:(NSString *)Code phone:(NSString *)phone Name:(NSString *)Name password:(NSString *)password{
    OSSPutObjectRequest *put = [OSSPutObjectRequest new];
    [self initALi];
    put.bucketName = @"dahan-img";
    
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:0];
    
    NSTimeInterval a = [date timeIntervalSince1970];
    
    NSInteger x= (NSInteger)a;
    
    date = [NSDate date];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd"];
    
    NSString *dateTime = [formatter stringFromDate:date];
    
    NSString *objectKey = [NSString stringWithFormat:@"Picture/head/%@/%ld_%d%d%d%d%d%d.jpg",dateTime,(long)x,arc4random()%10,arc4random()%10,arc4random()%10,arc4random()%10,arc4random()%10,arc4random()%10];
    
    NSString *str = [NSString stringWithFormat:@"http://img.dahan.cn/%@",objectKey];
    
    imgUrl = [NSString stringWithFormat:@"http://dahan-img.oss-cn-shenzhen.aliyuncs.com/%@",objectKey];
    _2RegistViewController *vc = [[_2RegistViewController alloc] init:Code :phone];
    [vc Alarequest2WithData:imgUrl password:password name:Name];
    
    NSLog(imgUrl);
    put.objectKey = objectKey;
    put.uploadingData = data;
    put.uploadProgress = ^(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend) {
        NSLog(@"%lld,%lld,%lld",bytesSent,totalBytesSent,totalBytesExpectedToSend);
    };
    
    OSSTask *putTask = [_client putObject:put];
    
    [putTask continueWithBlock:^id _Nullable(OSSTask * _Nonnull task) {
        NSLog(@"1");
        if (!task.error) {
            NSLog(@"上传成功");
            //            [SVProgressHUD showSuccessWithStatus:@"上传成功"]
          //  [self changeInfo];
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:@"上传失败,请确认网络后再试"];
        }
        
        return nil;
    }];
    
    //    [putTask waitUntilFinished];
}

#pragma mark - 获取服务器数据
-(void)getUserMessage{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    
    
    
    NSString *cookie = [user objectForKey:@"Cookie"];
   // NSString *iid = [user objectForKey:@"account"];
  //  NSLog(@"%@",iid);
  
    
    
    [manager.requestSerializer setValue:cookie forHTTPHeaderField:@"Cookie"];
    
    //    NSDictionary *parameters = @{@"page":@"1",@"client_type":@"1"};
    
    [manager POST:@"http://dahan-api.heiyou.net/index.php/home/user/getUserInfo" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseData)
     {
         [SVProgressHUD dismiss];
         NSLog(@"%@",responseData);
         
         LoadViewController *vc = [[LoadViewController alloc]init];
         NSLog(@"%@");
        
         
        
     //     _userInfoDic = responseJSON;
        NSString *iid = [_userInfoDic[@"result"] string];
         NSLog(@"%@",iid);
//         if (iid == @"<null>"){
//             [SVProgressHUD showErrorWithStatus:@"用户未登录"];
//             [self dismissViewControllerAnimated:YES completion:nil];
//         }
//         
         NSString *str = [NSString stringWithFormat:@"%@",_userInfoDic[@"account"]];
         NSLog(@"%@",str);
         if ([_userInfoDic[@"status"] integerValue] == 200)
         {
             NSLog(@"11");
             if([str isEqualToString:@"(null)"])
             {
                 UIAlertController *alter = [UIAlertController alertControllerWithTitle:@"提示" message:@"您未登录，无法编辑资料" preferredStyle:UIAlertControllerStyleAlert];
                 UIAlertAction *cacelAction = [UIAlertAction actionWithTitle:@"暂不登录" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                     [self dismissViewControllerAnimated:YES completion:nil];
                 }];
                 UIAlertAction *okeyAction = [UIAlertAction actionWithTitle:@"前往登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                     LoginViewController *vc = [[LoginViewController alloc] init];
                     
                     UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
                     vc.navigationController.navigationBar.hidden = YES;
                     
                     [self presentViewController:nav animated:YES completion:nil];
                 }];
                 
                 [alter addAction:cacelAction];
                 [alter addAction:okeyAction];
                 
                 [self presentViewController:alter animated:YES completion:nil];
             }
             else
             {
             dispatch_async(dispatch_get_main_queue(), ^{
                 [self.view addSubview:[self editView:_userInfoDic[@"result"]]];
             });
             }
         }else{
            [SVProgressHUD showErrorWithStatus:@"获取失败"];
             [self dismissViewControllerAnimated:YES completion:nil];
         }
         
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         [SVProgressHUD showErrorWithStatus:@"获取失败"];
         dispatch_async(dispatch_get_main_queue(), ^{
             [self.view addSubview:self.editView];
         });
         NSLog(@"失败");
     }];

}

-(void)changeInfo{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    
    
    
    NSString *cookie = [user objectForKey:@"Cookie"];
    
    NSLog(@"%@",cookie);
    
    [manager.requestSerializer setValue:cookie forHTTPHeaderField:@"Cookie"];
    NSDictionary *parameters;
    ;
    if (isChoose)
    {
        parameters = @{
                       @"img":imgUrl,
                       @"name":[[NSString stringWithFormat:@"%@",self.editView.nameTextField.text] isEqualToString:@""]?self.editView.nameTextField.placeholder:self.editView.nameTextField.text,
                       @"sex":self.editView.lastBtn.tag == EditViewButtonTypeMale?@"男":@"女"
                       };
    }
    else
    {
        parameters = @{
                       @"img":self.editView.userInfo[@"img"],
                       @"name":[[NSString stringWithFormat:@"%@",self.editView.nameTextField.text] isEqualToString:@""]?self.editView.nameTextField.placeholder:self.editView.nameTextField.text,
                       @"sex":self.editView.lastBtn.tag == EditViewButtonTypeMale?@"男":@"女"
                       };
    }
        
    //    NSDictionary *parameters = @{@"page":@"1",@"client_type":@"1"};
    
    [manager POST:@"http://dahan-api.heiyou.net/index.php/home/user/EditData" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
     {
         NSLog(@"%@",responseObject);
         if ([responseObject[@"status"] integerValue] == 200 )
         {
             [SVProgressHUD showSuccessWithStatus:@"资料修改成功"];
             if (isChoose)
             {
                 [[NSUserDefaults standardUserDefaults] setObject:imgUrl forKey:@"img"];
             }
             [[NSUserDefaults standardUserDefaults] setObject:[[NSString stringWithFormat:@"%@",self.editView.nameTextField.text] isEqualToString:@""]?self.editView.nameTextField.placeholder:self.editView.nameTextField.text forKey:@"name"];
             [[NSUserDefaults standardUserDefaults] setObject:self.editView.lastBtn.tag == EditViewButtonTypeMale?@"男":@"女" forKey:@"sex"];
             [self dismissViewControllerAnimated:YES completion:nil];

         }
         else
         {
             [SVProgressHUD showErrorWithStatus:@"资料与原资料相同，未做修改"];
         }
         
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         [SVProgressHUD showErrorWithStatus:@"修改失败，请稍后再试"];

         NSLog(@"失败");
     }];

}

#pragma mark - EditViewDelegate协议实现
-(void)clickEditViewBtn:(UIButton *)btn{
    if (btn.tag == EditViewButtonTypeFemale ||btn.tag == EditViewButtonTypeMale)
    {
        self.editView.lastBtn.selected = NO;
        
        btn.selected = YES;
        
        self.editView.lastBtn = btn;
    }
    else if (btn.tag == EditViewButtonTypeSave)
    {
        [SVProgressHUD showWithStatus:@"上传资料中"];
        if (isChoose)
        {
            CGFloat fixelW = CGImageGetWidth(image.CGImage);
            CGFloat fixelH = CGImageGetHeight(image.CGImage);
            
            if (fixelW > 1280 && fixelH > 720)
            {
                image = [self imageByScalingAndCroppingForSize:CGSizeMake(1280, 720) WithSourceImage:image];
            }else if (fixelW > 1280 && fixelH <= 720)
            {
                image = [self imageByScalingAndCroppingForSize:CGSizeMake(1280, fixelH) WithSourceImage:image];
            }else if(fixelW <= 1280 && fixelH > 720)
            {
                image = [self imageByScalingAndCroppingForSize:CGSizeMake(fixelW, 720) WithSourceImage:image];
            }
            
            NSData *data = UIImageJPEGRepresentation(image,0.5);
            
            [self updateToALi:data];
    
        }
        else
        {
            [self changeInfo];
        }
    }
}

-(void)chooseHeaderImg{
    
    UIImagePickerController *imagePickerVC = [[UIImagePickerController alloc] init];
    
    imagePickerVC.delegate = self;
    
    //设置是否需要做图片编辑
    imagePickerVC.allowsEditing = YES;
    
    //判断数据来源是否可用
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        
        //设置数据来源
        imagePickerVC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
        //打开相机/相册/图库
        [self presentViewController:imagePickerVC animated:YES completion:nil];
    }
    
}

#pragma mark - UIImagePickerController协议实现
//取消选择
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    
    [picker dismissViewControllerAnimated:YES completion:nil];

}

//选择完成
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    [self.editView.headerImgBtn setBackgroundImage:[info objectForKey:UIImagePickerControllerOriginalImage] forState:UIControlStateNormal];
    
    image = [info objectForKey:UIImagePickerControllerOriginalImage];
    isChoose = true;
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 禁止屏幕旋转
-(BOOL)shouldAutorotate{
    return NO;
}

#pragma mark - 其他函数
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.editView.nameTextField resignFirstResponder];
}

//图片压缩到指定大小
-(UIImage *)imageByScalingAndCroppingForSize:(CGSize)targetSize WithSourceImage:(UIImage *)sourceImage{
    UIImage *newImage = nil;
    
    CGSize imageSize = sourceImage.size;
    
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    
    CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);
    
    if (!CGSizeEqualToSize(imageSize, targetSize)) {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor) {
            scaleFactor = widthFactor;
        }else{
            scaleFactor = heightFactor;
        }
        
        scaledWidth = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        if (widthFactor > heightFactor) {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }else if (widthFactor < heightFactor){
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    
    UIGraphicsBeginImageContext(targetSize);
    
    CGRect thumbnailRect = CGRectZero;
    
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    if (newImage == nil) {
        NSLog(@"无法压缩");
    }
    UIGraphicsEndImageContext();
    
    return newImage;
}

@end
